//
//  JALoginController.swift
//  JAWeiBo
//
//  Created by Arvin on 17/4/4.
//  Copyright © 2017年 Arvin. All rights reserved.
//

import UIKit

class JALoginController: UIViewController {
    
    ///webView的懒加载属性
    lazy var webView: UIWebView = {
        let webView = UIWebView(frame: self.view.bounds)
        webView.delegate = self
        return webView
        
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white
        
        //设置UI
        setupUI()
        
        //加载数据
        loadLoginPage()
    }

    fileprivate func loadLoginPage() {

        
        let url = URL(string: NetworkTool.shared.loginURL)
        
        let request = URLRequest(url: url!)
        
        webView.loadRequest(request)
        
    }
    
}

// MARK: - 事件处理
extension JALoginController {
    @objc fileprivate func back() {
        dismiss(animated: true, completion: nil)
    }
    
}

// MARK: - 设置UI
extension JALoginController {
    @objc fileprivate func setupUI() {
        
        //添加webView
        self.view.addSubview(webView)
        
        //设置返回按钮
        let buttonItem = UIBarButtonItem(title:"返回", style: .plain, target: self, action: #selector(back))
        navigationItem.leftBarButtonItem = buttonItem
    }
}


//MARK: - UIWebViewDelegate
extension JALoginController: UIWebViewDelegate {
    
    //网页将要加载时执行,如果return true, 则request请求成功, 否则失败
    func webView(_ webView: UIWebView,shouldStartLoadWith request: URLRequest,navigationType: UIWebViewNavigationType) -> Bool {
       
        
        //1. 判断url是否是回调页, 如果是回调页, 页面不能显示出来, return false
        if let urlString = request.url?.absoluteString,
            urlString.hasPrefix(redirectURI) == true, let query = request.url?.query {
            
            //2. 判断点击的是取消还是授权按钮: 如果参数的的前缀是 'code=', 说明点击是授权按钮
            if(query.hasPrefix("code=")){
                
                //拦截code
                //获取到"code="子串的range
                //range是一个index的区间值(lowerBound..<upperBound), upperBound取的是区间值的右边的index的值; lowerBounds可以取到械的index的值
                let subrange = urlString.range(of: "code=")
                let code = urlString.substring(from: (subrange?.upperBound)!)
               
                
                //使用code获取token
                NetworkTool.shared.requestToken(code: code, callBack: { (tokenDic) in
                    //获取用户名和头像
                    if let tokenDic = tokenDic as?[String: Any],
                        let uid = tokenDic["uid"] as? String,
                        let token = tokenDic["access_token"] as? String {
                        NetworkTool.shared.reqeustUser(uid: uid, accessToken: token, callBack: { (userDic) in
                            
                            //判断userDic是否有值
                            if var userDic = userDic as? [String: Any] {
                                //合并字典
                                for (k, v) in tokenDic {
                                    userDic[k] = v
                                }
                                
                                //保存用户信息
                                JAUserAccount.shared.save(dict: userDic)
                                
                                //登录成功后发送通知
                                let notification = Notification(name: loginSuccessNotification)
                                NotificationCenter.default.post(notification)
                                
                                self.back()
                            }else {
                                //没有成功获取到user信息
                                self.back()
                            }
                        })
                    } else {
                        //没有成功获取到token
                        self.back()
                    }
                })
            }else {//点击的是取消按钮
                self.back()
            }
            
            return false
        }
        
        return true
    }
    
      /// 网页加载成功之后执行
    func webViewDidFinishLoad(_ webView: UIWebView) {
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value='\(wbuserName)';document.getElementById('passwd').value='\(wbPassword)'")
    }
    
}
